<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button @click="addRoledialogVisible = true" plain type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <el-table-column align="center" type="expand">
          <template slot-scope="scope">
            <!-- 1 级 -->
            <el-row
              :class="['bdborder', 'vcenter',index1 === 0 ? 'btborder' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRightById(scope.row,item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 2 级 -->
                <el-row
                  :class="['vcenter', index2 === 0 ? '' : 'btborder']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 3 级 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色管理"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              @click="editRolesHandle(scope.row.id)"
              size="mini"
              plain
              type="primary"
              icon="el-icon-edit"
            >编辑</el-button>
            <el-button
              @click="removeRolesById(scope.row.id)"
              size="mini"
              plain
              type="danger"
              icon="el-icon-delete"
            >删除</el-button>
            <el-button
              @click="setRoles(scope.row)"
              size="mini"
              plain
              type="warning"
              icon="el-icon-setting"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoledialogVisible"
      width="50%"
      @close="addRoledialogClosed"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoledialogVisible"
      width="50%"
      @close="editRoledialogClosed"
    >
      <el-form
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRoledialogVisible"
      width="50%"
      @close="setRoledialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="rightsKeysArr"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoledialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表数据
      roleList: [],
      // 控制添加角色对话框的显示与隐藏
      addRoledialogVisible: false,
      // 添加角色数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则对象
      addRoleFormRules: {
        // 角色名称验证规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        // 角色描述验证规则
        roleDesc: [{ min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }]
      },
      // 控制添加角色对话框的显示与隐藏
      editRoledialogVisible: false,
      // 添加角色数据对象
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则对象
      editRoleFormRules: {
        // 角色名称验证规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        // 角色描述验证规则
        roleDesc: [{ min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }]
      },
      // 控制分配权限对话框的显示与隐藏
      setRoledialogVisible: false,
      // 所有权限的数据
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 已经选中的权限的id值数组
      rightsKeysArr: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created() {
    // 调用获取角色列表数据的方法
    this.getRoleList()
  },
  methods: {
    // 获取角色列表数据
    async getRoleList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },

    // 移除权限
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      role.children = res.data
    },

    // 添加角色表单重置
    addRoledialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    // 添加角色
    addRoles() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('/roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addRoledialogVisible = false
        this.getRoleList()
      })
    },

    // 点击编辑按钮，根据 ID 查询角色
    async editRolesHandle(id) {
      const { data: res } = await this.$http.get(`/roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRoleForm = res.data
      this.editRoledialogVisible = true
    },

    // 编辑角色表单重置
    editRoledialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },

    // 编辑角色
    editRole() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`/roles/${this.editRoleForm.roleId}`, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editRoledialogVisible = false
        this.getRoleList()
      })
    },

    // 删除角色
    async removeRolesById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.error('您取消了删除')
      }

      const { data: res } = await this.$http.delete(`/roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
    },

    // 分配权限
    async setRoles(roles) {
      this.roleId = roles.id
      const { data: res } = await this.$http.get('/rights/tree')

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeayKey(roles, this.rightsKeysArr)
      this.setRoledialogVisible = true
    },
    // 获取角色下所有三级权限的id
    getLeayKey(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeayKey(item, arr))
    },
    // 监听分配权限弹框的关闭事件
    setRoledialogClosed() {
      this.rightsKeysArr = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRoledialogVisible = false
      this.getRoleList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.btborder {
  border-top: 1px solid #eee;
}
.bdborder {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
